package cmd

import (
	"fmt"
	"gitee.com/jinmingzhi/kit/rdb"
	"github.com/gchaincl/dotsql"
	"github.com/jmoiron/sqlx"
	"github.com/spf13/cobra"
	"time"
)

var run = &cobra.Command{
	Use:   "exec",
	Short: "Execute SQL",
	Long:  `migration exec <sql file>`,
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		db := sqlx.MustConnect("mysql", rdb.MustLoadConfig().DSN)
		dot, err := dotsql.LoadFromFile(args[0])
		if err != nil {
			fmt.Println("loadfromfile failed", err)
			return
		}

		m := dot.QueryMap()

		for k, _ := range m {
			_, err := dot.Exec(db, k)
			if err != nil {
				fmt.Println("sql key:", k)
				fmt.Println("sql exec failed", err)
				return
			}
			time.Sleep(time.Second)
		}
	},
}

func init() {
	rootCmd.AddCommand(run)
}
